import config from '@/config/app'
import store from "@/store"
/**
 * @description 获取元素节点信息（在组件中的元素必须要传ctx）
 * @param  { String } selector 选择器 '.app' | '#app'
 * @param  { Boolean } all 是否多选
 * @param  { ctx } context 当前组件实例
 */
export const getRect = (selector, all = false, context) => {
  return new Promise((resolve, reject) => {
    let qurey = uni.createSelectorQuery()
    if (context) {
      qurey = uni.createSelectorQuery().in(context)
    }
    qurey[all ? 'selectAll' : 'select'](selector)
      .boundingClientRect(function(rect) {
        if (all && Array.isArray(rect) && rect.length) {
          return resolve(rect)
        }
        if (!all && rect) {
          return resolve(rect)
        }
        reject('找不到元素')
      })
      .exec()
  })
}



export function navigateTo(link, navigateType = 'navigateTo') {
  const url = link.query ? `${link.path}?${objectToQuery(link.query)}` : link.path

  console.log(url, link);
  navigateType == 'navigateTo' && uni.navigateTo({
    url,
    fail(e) {
      console.error(e);
    }
  })
  navigateType == 'reLaunch' && uni.reLaunch({
    url
  })
}

export function copy(text) {
  uni.setClipboardData({
    data: String(text)
  })

}

export async function saveImageToPhotosAlbum(url) {
  if (!url) return uni.$u.toast('图片错误')
  //#ifdef H5
  uni.$u.toast('长按图片保存')
  //#endif
  //#ifndef H5
  try {
    const res = await uni.downloadFile({
      url,
      timeout: 10000
    })
    await uni.saveImageToPhotosAlbum({
      filePath: res.tempFilePath
    })
    uni.showToast({
      title: '保存成功',
      icon: 'success'
    })
  } catch (error) {
    uni.$u.toast(error.errMsg || '保存失败')
  }
  //#endif
}


export function uploadFile(path) {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: config.baseUrl + '/upload/image',
      filePath: path,
      name: 'file',
      header: {
        token: store.state.token || null
      },
      fileType: 'image',
      cloudPath: '',
      success: res => {
        console.log('uploadFile res ==> ', res)
        let data = JSON.parse(res.data);

        if (data.code == 1) {
          resolve(data.data);
        } else {
          reject()
        }
      },
      fail: (err) => {
        console.log(err)
        reject()
      }
    });
  });
}

/**
 * @description 格式化输出价格
 * @param  { string } price 价格
 * @param  { string } take 小数点操作
 * @param  { string } prec 小数位补
 */
export function formatPrice({
  price,
  take = 'all',
  prec = undefined
}) {
  let [integer, decimals = ''] = (price + '').split('.')

  // 小数位补
  if (prec !== undefined) {
    const LEN = decimals.length
    for (let i = prec - LEN; i > 0; --i) decimals += '0'
    decimals = decimals.substr(0, prec)
  }

  switch (take) {
    case 'int':
      return integer
    case 'dec':
      return decimals
    case 'all':
      return integer + '.' + decimals
  }
}

/**
 * @description 组合异步任务
 * @param  { string } task 异步任务
 */

export function series(...task) {
  return function() {
    return new Promise((resolve, reject) => {
      const iteratorTask = task.values()
      const next = (res) => {
        const nextTask = iteratorTask.next()
        if (nextTask.done) {
          resolve(res)
        } else {
          Promise.resolve(nextTask.value(res)).then(next).catch(reject)
        }
      }
      next()
    })
  }
}